fs     = require 'fs'
{exec} = require 'child_process'

appFiles  = [
  # omit src/ and .coffee to make the below lines a little shorter
  'services'
  'controllers'
  'directives'
  'filters'
  'app'
]

task 'build', 'Build single application file from source files', ->
  appContents = new Array remaining = appFiles.length
  for file, index in appFiles then do (file, index) ->
    fs.readFile "coffee/src/#{file}.coffee", 'utf8', (err, fileContents) ->
      throw err if err
      appContents[index] = fileContents
      process() if --remaining is 0
  process = ->
    fs.writeFile 'coffee/bin/app.coffee', appContents.join('\n\n'), 'utf8', (err) ->
    # fs.writeFile 'assets/js/app.coffee', appContents.join('\n\n'), 'utf8', (err) ->
      throw err if err
      exec 'coffee --compile coffee/bin/app.coffee', (err, stdout, stderr) ->
      # exec 'coffee --compile assets/js/app.coffee', (err, stdout, stderr) ->
        throw err if err
        console.log stdout + stderr
        fs.unlink 'coffee/bin/app.coffee', (err) ->
        # fs.unlink 'assets/js/app.coffee', (err) ->
          if err
            throw err
          else
            minify()
            console.log 'minify\n'
          console.log 'Done.'
  minify = ->
    exec 'java -jar "compiler.jar" --js coffee/bin/app.js --js_output_file assets/js/app.js', (err, stdout, stderr) ->
      throw err if err
      console.log stdout + stderr
      console.log 'Done.'